from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework import status
from admincharge.models import ChargeAdmin
from rest_framework.exceptions import NotFound


class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    # 后台的登录认证
    def validate(self, attrs):
        username = attrs['username']
        password = attrs['password']
        user = ChargeAdmin.objects.filter(username=username, password=password).first()
        print('user',user)
        if not user:
            result = {
                "code": 4000,
                "msg": "账号/密码不正确",
            }
            return result
        status = user.status
        if status =='2':
            result = {
                'code':4000,
                'msg':'账号已被禁用'
            }
            return result
        refresh = self.get_token(user)
        data = {"userId": user.id,
                "user_name": user.nick_name,
                'password': user.password,
                "token": str(refresh.access_token),
                'exp':refresh.access_token.payload['exp'],
                "refresh": str(refresh),
                "code": 2000,
                'msg': '登陆成功'
                }
        print(data)
        return data
